package com.hzvdvmc.autosale.util;

/**
 * Created by william on 2017/12/27.
 * 加密工具
 * 传入command+data
 */

public class EncodeUtil {
    //正式
    public static char[][] VDKEY = {
            {'1', '2', '3', '4', '5', '6', '7', '8'},
            {'8', '7', '6', '5', '4', '3', '2', '1'},
            {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'},
            {'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A'},
            {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'},
            {'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'},
            {'f', 'y', '1', '2', '3', '4', '5', '6'},
            {'1', '2', '3', '4', '5', '6', 'y', 'f'}};

    //测试用
//    public static char[][] VDKEY ={
//            { '1','3','4','6','7','5','4','3'},
//            {'f','j','e','p','o','i','z','v'},
//            {'K','J','D','A','O','I','E','S'},
//            {'9','8','0','7','4','6','u','i'},
//            {'a','e','i','9','7','8','3','2'},
//            {'l','k','d','f','a','i','e','d'},
//            {'9','8','0','3','4','3','t','e'},
//            {'l','k','k','d','s','a','8','8'}
//    };


    /**
     * 加密
     * @param data 16进制 30
     * @return 16进制08
     */
    public static String encoded(String data) {
        int cKeyNum = data.length() /2 % 8;
        int iKeyLen = 8;

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length(); i += 2) {
            String hex = data.substring(i, i + 2);
            char c = (char) Integer.parseInt(hex, 16);

            c += VDKEY[cKeyNum][i / 2 % iKeyLen] % 4;
            c = (char) (c ^ VDKEY[cKeyNum][i / 2 % iKeyLen]);
            String hexs = Integer.toHexString((int) c);
            if(hexs.length() == 1){
                hexs = "0" + hexs;
            }
            sb.append(hexs);
        }
        return sb.toString();
    }


    /**
     * 解密
     * @param data 16进制08
     * @return 16进制30
     */
    public static String decoded(String data) {
        int cKeyNum = data.length() /2% 8;
        int iKeyLen = 8;

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length(); i += 2) {
            String hex = data.substring(i, i + 2);
            char c = (char) Integer.parseInt(hex, 16);

            c = (char) (c ^ VDKEY[cKeyNum][i / 2 % iKeyLen]);
            c -= VDKEY[cKeyNum][i / 2 % iKeyLen] % 4;

            String hexs = Integer.toHexString((int) c);
            if(hexs.length() == 1){
                hexs = "0" + hexs;
            }
            sb.append(hexs);
        }
        return sb.toString();
    }
}
